<template>
  <view class="create-address page">
    <div class="page-title">收件人信息 Recipient Information</div>

    <div class="form-box">
      <div class="wrap">
        <div class="form-item">
          <div class="label">城市 City</div>
          <div class="value">
            <div class="add-btn" @click="openPicker">
              {{ addrInfo.province + addrInfo.city + addrInfo.district }}
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="label">详细地址 Address</div>
          <div class="value">
            <input v-model="addrInfo.placeInfo" class="value-input" type="text" />
          </div>
        </div>
        <div class="form-item">
          <div class="label">收货人姓名 Recipient Name</div>
          <div class="value">
            <input class="value-input" v-model="addrInfo.name" type="text" />
          </div>
        </div>
        <div class="form-item">
          <div class="label">手机号 Phone Number</div>
          <div class="value">
            <input class="value-input" v-model="addrInfo.phone" type="number" />
          </div>
        </div>
        <div class="form-item">
          <div class="check-ele" :class="{ active: addrInfo.isDefault == 1 }" @click="changeDefault">
            <div class="checkbox"></div>
            <div class="te">默认地址 Default Addresses</div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-control-box">
      <div class="bottom-control-container">
        <div class="wrap">
          <div class="bottom-control-btn" @click="goBack">取消 Cancel</div>
          <div class="bottom-control-btn" @click="saveAddrssInfo">保存 Save</div>
        </div>
        <bottom-safe-area></bottom-safe-area>
      </div>
      <div>
        <div style="height: 100rpx"></div>
        <bottom-safe-area></bottom-safe-area>
      </div>
    </div>

    <uv-picker
      ref="picker"
      :columns="addressList"
      :loading="loading"
      keyName="name"
      @change="change"
      @confirm="confirm"
    >
    </uv-picker>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed } from 'vue'
import { addressList, saveAddrss, addressInfo } from '@/utils/api/address'
import { mobile } from '@/utils/reg'
import regions from '@/utils/regions.json'
import { onLoad } from '@dcloudio/uni-app'
const picker = ref<any>()
let isEdit = false
let id = ''
let provinces = ref<any>([])
let citys = ref<any>([])
let areas = ref<any>([])
let pickerValue = ref<any>([0, 0, 0])
let defaultValue = ref<any>([3442, 1, 2])
const addressList = computed(() => {
  return [provinces.value, citys.value, areas.value]
})
interface AddressInfo {
  id: string | number
  city: string
  district: string
  name: string
  phone: string | number
  placeInfo: string
  province: string
  isDefault: string | number
}

const addrInfo = reactive<AddressInfo>({
  city: '',
  district: '',
  name: '',
  phone: '',
  placeInfo: '',
  province: '',
  isDefault: -1
})

const goBack = () => {
  uni.navigateBack()
}
const saveAddrssInfo = async () => {
  console.log('addrInfo:', addrInfo)
  if (addrInfo.province === '') {
    uni.showToast({ title: '请选择省', icon: 'none' })
    return
  }
  if (addrInfo.city === '') {
    uni.showToast({ title: '请选择城市', icon: 'none' })
    return
  }
  if (addrInfo.district === '') {
    uni.showToast({ title: '请选择区县', icon: 'none' })
    return
  }
  if (addrInfo.placeInfo === '') {
    uni.showToast({ title: '请填写详细地址', icon: 'none' })
    return
  }
  if (addrInfo.name === '') {
    uni.showToast({ title: '请填写收货人姓名', icon: 'none' })
    return
  }
  if (addrInfo.phone === '') {
    uni.showToast({ title: '请填写手机号', icon: 'none' })
    return
  }
  if (!mobile(addrInfo.phone)) {
    uni.showToast({ title: '请填写正确的手机号', icon: 'none' })
    return
  }

  const res = await saveAddrss(addrInfo)
  uni.navigateBack()
  console.log('新增地址:', res)
}

let loading = ref<boolean>(false)
const getData = () => {
  loading.value = true
  try {
    console.log('获取的数据：', regions)
    provinces.value = regions.sort((left, right) => (Number(left.code) > Number(right.code) ? 1 : -1))
    console.log('省的数据:', provinces.value)
    handlePickValueDefault()
    setTimeout(() => {
      loading.value = false
    }, 200)
  } catch (err) {
    console.error('处理地区数据失败:', err)
    uni.showToast({ title: '加载地区数据失败', icon: 'none' })
  }
}

const handlePickValueDefault = () => {
  // 设置省
  pickerValue.value[0] = provinces.value.findIndex((item) => Number(item.id) === defaultValue.value[0])
  // 设置市
  citys.value = provinces.value[pickerValue.value[0]]?.children || []
  pickerValue.value[1] = citys.value.findIndex((item) => Number(item.id) === defaultValue.value[1])
  // 设置区
  areas.value = citys.value[pickerValue.value[1]]?.children || []
  pickerValue.value[2] = areas.value.findIndex((item) => Number(item.id) === defaultValue.value[2])
  // 重置下位置
  picker.value.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]], true)
}

const change = (e) => {
  if (loading.value) return
  const { columnIndex, index, indexs } = e
  // 改变了省
  if (columnIndex === 0) {
    citys.value = provinces.value[index]?.children || []
    areas.value = citys.value[0]?.children || []
    picker.value.setIndexs([index, 0, 0], true)
  } else if (columnIndex === 1) {
    areas.value = citys.value[index]?.children || []
    picker.value.setIndexs(indexs, true)
  }
}
const confirm = (e) => {
  console.log('确认选择的地区：', e)
  addrInfo.province = e.value[0].name
  addrInfo.city = e.value[1].name
  addrInfo.district = e.value[2].name
}
const openPicker = () => {
  picker.value.open()
  handlePickValueDefault()
}

const getaddrInfo = async () => {
  const res = await addrInfo({ id: id })
  console.log('获取的收货地址信息：', res)
  if (res.code === 200) {
    addrInfo.placeInfo = res.placeInfo
    addrInfo.name = res.name
    addrInfo.phone = res.phone
    addrInfo.province = res.province
    addrInfo.city = res.city
    addrInfo.district = res.district
    // defaultValue.value = [res.provinceId, res.cityId, res.districtId]
  }
}

const changeDefault = () => {
  addrInfo.isDefault = addrInfo.isDefault === 1 ? -1 : 1
}
onLoad((option) => {
  if (option && option.id) {
    isEdit = true
    id = option.id
    addrInfo.id = option.id
    getaddrInfo()
  }
  setTimeout(() => {
    getData()
  }, 100)
})
</script>

<style lang="scss" scoped>
@import './addAddress.scss';
</style>
